<?php

namespace business\elasticsearch\services;


use business\elasticsearch\models\BigDataTakenLandModel;

class BigDataTakenLandService
{
    private static $IS_DELETED = 1;//删除

    public function getDataList(
        $keyword,
        $province,
        $city,
        $companyType,
        array $landType,
        $areaLower,
        $areaUpper,
        $unitPriceLower,
        $unitPriceUpper,
        $landPriceLower,
        $landPriceUpper,
        $isPriceGtAvg,
        $area,
        $createdTime,
        $tags,
        $companyArea, $takeLandDateStart, $takeLandDateEnd, $organizingCode,
        $page,
        $pageSize
    )
    {
        $condition = $this->constructCondition(
            $keyword,
            $province,
            $city,
            $companyType,
            $landType,
            $areaLower,
            $areaUpper,
            $unitPriceLower,
            $unitPriceUpper,
            $landPriceLower,
            $landPriceUpper,
            $isPriceGtAvg,
            $area,
            $createdTime,
            $tags,
            $companyArea, $takeLandDateStart, $takeLandDateEnd, $organizingCode
        );
//        echo json_encode($condition);exit;
        $query = BigDataTakenLandModel::find()
            ->query($condition);

        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "land_title" => new \stdClass(),
                "developer_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['take_land_date' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $searchData = $query->createCommand()->search();
        //数据处理
        $total = 0;
        $list = [];
        if (!empty($searchData)) {
            $data = $searchData["hits"]["hits"];
            $total = $searchData["hits"]["total"];
            foreach ($data as $dv) {
                $tmp = $dv['_source'];
                $tmp['nameSuggest'] = $tmp['land_title'];
                if (!empty($dv['highlight'])) {
                    foreach ($dv['highlight'] as $key => $value) {
                        $tmp[$key . 'HL'] = $value[0] ?? '';
                    }
                }

                $tmp = $this->formatTakenLand($tmp);
                $list[] = $tmp;
            }
        }

        return ['total' => $total, 'list' => $list];
    }

    private function constructCondition(
        $keyword = [],
        $province = [],
        $city = [],
        $companyType = [],
        $landType = [],
        $areaLower = '',
        $areaUpper = '',
        $unitPriceLower = '',
        $unitPriceUpper = '',
        $landPriceLower = '',
        $landPriceUpper = '',
        $isPriceGtAvg = [],
        $area = [],
        $createdTime = '',
        $tags = [],
        $companyArea = [], $takeLandDateStart = '', $takeLandDateEnd = '', $organizingCode = []
    )
    {
        $query = [];
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
        $must = [];
        $mustNot = [];
        $query['function_score']['query']['bool']['must'] = &$must;
        $query['function_score']['query']['bool']['must_not'] = &$mustNot;

        //不等于删除状态
        $mustNot[] = ["term" => ["is_deleted" => self::$IS_DELETED]];

        //项目关键词
        if (!empty($keyword)) {
            $keyShould = [];
            $must[] = ['bool' => ['should' => &$keyShould]];

            foreach ($keyword as $k) {

                $titleBool = [];
                $titleBool[] = [
                    'match_phrase' => ['land_title' => ["query" => $k, "boost" => 6, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $titleBool]];

                $projectBool = [];
                $projectBool[] = [
                    'match_phrase' => ['project_name' => ["query" => $k, "boost" => 3, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $projectBool]];

                $developerBool = [];
                $developerBool[] = [
                    'match_phrase' => ['developer_name' => ["query" => $k, "boost" => 3, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $developerBool]];

            }
        }


        // 省市
        if (!empty($province)) {
            $must[] = ["terms" => ['province_code' => $province]];
        }
        if (!empty($city)) {
            $must[] = ["terms" => ['city_code' => $city]];
        }

        //地区
        if (!empty($area)) {
            $shouldArea = [];
            $must[] = ['bool' => ['should' => &$shouldArea]];
            $shouldArea[] = ["terms" => ['province_code' => $area]];
            $shouldArea[] = ["terms" => ['city_code' => $area]];
        }

        //企业地区
        if (!empty($companyArea)) {
            $shouldArea = [];
            $must[] = ['bool' => ['should' => &$shouldArea]];
            $shouldArea[] = ["terms" => ['company_province_code' => $companyArea]];
            $shouldArea[] = ["terms" => ['company_city_code' => $companyArea]];
        }

        //企业类型
        if (!empty($companyType)) {
            $must[] = ["terms" => ['company_type_label' => $companyType]];
        }

        // 公司社会信用代码
        if (!empty($organizingCode)) {
            $must[] = ["terms" => ['organizing_code.keyword' => $organizingCode]];
        }

        //高端项目标签
        if (!empty($isPriceGtAvg)) {
            $must[] = ["terms" => ['is_price_gt_avg' => $isPriceGtAvg]];
        }

        //土地类型
        if (is_array($landType) && count($landType) > 0) {
            $nestedLandUsageQuery['bool']['filter']['terms']['land_usage_label.label.keyword'] = $landType;
            $must[] = [
                'nested' => [
                    'path' => 'land_usage_label',
                    'query' => $nestedLandUsageQuery
                ]
            ];
        }

        // 拿地面积
        $areaRange = [];
        if (!empty($areaLower)) {
            $areaRange['gte'] = $areaLower;
        }
        if (!empty($areaUpper)) {
            $areaRange['lte'] = $areaUpper;
        }
        if (!empty($areaRange)) {
            $must[] = ['range' => ['all_area' => $areaRange]];
        }

        // 单价区间
        $priceRange = [];
        if (!empty($unitPriceLower)) {
            $priceRange['gte'] = $unitPriceLower;
        }
        if (!empty($unitPriceUpper)) {
            $priceRange['lte'] = $unitPriceUpper;
        }
        if (!empty($priceRange)) {
            $must[] = ['range' => ['land_unit_price' => $priceRange]];
        }

        // 成交区间　
        $landPriceRange = [];
        if (!empty($landPriceLower)) {
            $landPriceRange['gte'] = $landPriceLower;
        }
        if (!empty($landPriceUpper)) {
            $landPriceRange['lte'] = $landPriceUpper;
        }
        if (!empty($landPriceRange)) {
            $must[] = ['range' => ['take_land_price' => $landPriceRange]];
        }

        if (!empty($createdTime)) {
            $dateRange = [];
            $dateRange['from'] = $createdTime;
            $dateRange['to'] = date('Y-m-d H:i:s', time());
            $must[] = ['range' => ['created_at' => $dateRange]];
        }

        //拿地日期
        if (!empty($takeLandDateStart) && !empty($takeLandDateEnd)) {
            $dateRange = [];
            $dateRange['from'] = $takeLandDateStart;
            $dateRange['to'] = $takeLandDateEnd;
            $must[] = ['range' => ['take_land_date' => $dateRange]];
        }

        //标签
        if (!empty($tags)) {
            $tagShould = [];
            foreach ($tags as $k => $v) {
                if (!empty($v)) {
                    $tagShould[] = ['term' => [$k => $v]];
                }
            }
            $must[] = [
                'bool' => ['should' => $tagShould]
            ];
        }

        return $query;
    }


    public function guessNames($keyword, $pageSize)
    {
        $page = 1;
        $query = [];
        if (!empty($keyword)) {
            $query['function_score']['query']['bool']['must'][] = [
                'match_phrase' => ['land_title' => $keyword]
            ];
            //去除is_delete=1的数据
            $query['function_score']['query']['bool']['must_not'][] = [
                'term' => ['is_deleted' => self::$IS_DELETED]
            ];
        }

        $query = BigDataTakenLandModel::find()
            ->query($query);

        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "land_title" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        //数据处理
        $result = [];
        foreach ($data as $dv) {
            $item = array();
            $tmp = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['land_title'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $item['title'] = $tmp['land_title'];
            $item['titleHL'] = $tmp['land_titleHL'];
            $result[] = $item;
        }
        return $result;
    }

    public function formatTakenLand($data)
    {
        //1、显示赋值：因为 es 的值如果为 null 会没有字段
        $return_params = [
            'pulsar_time' => 'string',
            'id' => 'string',
            'src_uid' => 'string',
            'uid' => 'string',
            'organizing_code' => 'string',
            'developer_name' => 'string',
            'info_type' => 'string',
            'land_title' => 'string',
            'project_name' => 'string',
            'take_land_date' => 'string',
            'issue_date' => 'string',
            'planned_area' => 'string',
            'all_area' => 'string',
            'capablitity' => 'string',
            'land_usage' => 'string',
            'province' => 'string',
            'province_code' => 'string',
            'city' => 'string',
            'city_code' => 'string',
            'land_address' => 'string',
            'take_land_price' => 'string',
            'lng' => 'string',
            'lat' => 'string',
            'source_update_time' => 'string',
            'deliver_date' => 'string',
            'build_start_plan' => 'string',
            'build_end_plan' => 'string',
            'land_level' => 'string',
            'trade_type' => 'string',
            'use_time_description' => 'string',
            'authority' => 'string',
            'land_source' => 'string',
            'industry' => 'string',
            'region' => 'string',
            'land_unit_price' => 'string',
            'land_unit_price_avg' => 'string',
            'is_price_gt_avg' => 'string',
            'company_type_label' => 'string',
            'developer_id' => 'string',
            'developer_logo' => 'string',
            'purchase_demand_cnt_1year' => 'string',
            'cooperation_enterprise_cnt_1year' => 'string',
            'purchase_demand_cnt' => 'string',
            'cooperation_enterprise_cnt' => 'string',
            'developer_top_100_label' => 'string',
            'new_decorate_expand_label' => 'string',
            'new_land_usage_expand_label' => 'string',
            'new_area_expand_label' => 'string',
            'price_gt_avg_label' => 'string',
        ];

        foreach ($return_params as $rk => $rv) {
            $tmp = isset($data[$rk]) ? $data[$rk] : '';
            $tmp = $tmp === '1990-01-01 00:00:00' ? '' : $tmp;
            if ($rv == 'int') {
                $data[$rk] = (int)$tmp;
            } elseif ($rv == 'array') {
                $data[$rk] = empty($tmp) ? [] : $tmp;
            } else {
                $data[$rk] = $tmp;
            }

        }

        return $data;
    }
}
